package xyz.labmem.main.modular.common.service

import java.io.*
import java.net.URLEncoder
import javax.servlet.http.HttpServletResponse

/**
 * @Author lty
 * @Date 2022/1/10 11:11
 */
class FileDownLoadService {

    companion object {
        fun download(response: HttpServletResponse, file: File) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream")
            response.contentType = "application/octet-stream"
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.name, "UTF-8"))
            // 实现文件下载
            val buffer = ByteArray(1024)
            var fis: FileInputStream? = null
            var bis: BufferedInputStream? = null
            try {
                fis = FileInputStream(file)
                bis = BufferedInputStream(fis)
                val os: OutputStream = response.outputStream
                var i = bis.read(buffer)
                while (i != -1) {
                    os.write(buffer, 0, i)
                    i = bis.read(buffer)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                if (bis != null) {
                    try {
                        bis.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
                if (fis != null) {
                    try {
                        fis.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

}